package com.wh.message.sms.service.impl;

import com.wh.common.util.Result;
import com.wh.message.sms.in.SendSmsIn;
import com.wh.message.sms.service.JianZhouMessageService;
import com.wh.message.sms.utils.SmsConfig;
import com.wh.message.utils.ValidatorFactoryUtil;
import com.wh.msg.ResultCode;
import com.jianzhou.sdk.BusinessService;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;


/**
 * 建州短信实现类
 * @author 谢泽鹏
 * @version V1.0
 * @Package com.wh.message.sms.service.impl
 * @date 2014年10月8日 下午4:02:14
 * @Copyright 个人版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2018
 */
public class JianZhouMessageServiceImpl implements JianZhouMessageService {


    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 是否开启短信
     */
    @Value("#{settings['jianzhou.isOpen']}")
    private String isOpen;

    /**
     * 短信配置对象
     */
    private SmsConfig smsConfig;

    /**
     * 加载smsConfig
     * @param smsConfig
     */
    public void setSmsConfig(SmsConfig smsConfig) {
        this.smsConfig = smsConfig;
    }

    @Override
    public Result sendSms(SendSmsIn in) {
        logger.info("sendSms建州短信==============开始========");
        logger.info("sendSms建州短信sendSmsIn={}", JSONObject.fromObject(in).toString());
        logger.info("sendSms建州短信smsConfig={}",JSONObject.fromObject(smsConfig).toString());
        Result res = new Result();
        try {
            res= ValidatorFactoryUtil.validate(in);
            if(!ResultCode.RES_OK.equals(res.getResCode())){
                logger.info("sendSms建州短信，参数校验不通过,result={}",res);
                return res;
            }
            String content = in.getContent();
            int maxLength = smsConfig.getMaxLength();
            // 如果超过最大长度，则分成几条发送
            int count = content.length() / maxLength;
            int reminder = content.length() % maxLength;

            if (reminder != 0) {
                count += 1;
            }
            StringBuffer sbuId = new StringBuffer();
            StringBuffer sbuMsg = new StringBuffer();
            int i = 0;
            while (count > i) {
                boolean flage = doSend(
                        StringUtils.substring(content, i * maxLength, (i + 1)
                                * maxLength), in.getPhone());
                /**
                 * 只要有发送成功的都标识发送成功，失败的自己根据返回的编号进行处理
                 */
                if (flage) {
                    logger.info("sendSms建州短信,成功");
                    res.setResCode(ResultCode.RES_OK);
                } else {
                    res.setResCode(ResultCode.RES_NO);
                }
                i++;
            }
        }catch (Exception e){
            logger.error("sendSms建州短信出现异常msg={}",e.getMessage());
            e.printStackTrace();
            res.setResCode(ResultCode.RES_ERR);
            res.setResult(e.getMessage());
        }
        logger.info("sendSms建州短信==============结束========");
        return res;
    }

    private boolean doSend(String content, String phoneNo) {
        boolean falge=false;
        BusinessService bs = new BusinessService();
        bs.setWebService(smsConfig.getSmsUrl());//设置WebServie的地址
        /**
         * 发送手机短信
         */
        if(smsConfig.isTop()){
            content=smsConfig.getAutograph()+content;
        }else{
            content=content+smsConfig.getAutograph();
        }
        int reponse;
        if(!Boolean.parseBoolean(isOpen)){
            reponse = 0;
        }else{
            reponse = bs.sendBatchMessage(smsConfig.getAccount(), smsConfig.getPassword(), phoneNo, content);
            logger.info("建周返回状态："+reponse);
        }
        if(reponse>0){

            falge=true;
        }
       return falge;
    }



}
